package comm;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

import javax.swing.JTextArea;

import sun.awt.CharsetString;

public class SerialComm {
	JTextArea log;
	String message = "";
	
	public SerialComm(JTextArea logger, String port) {
		log = logger;
		try {
			connect(port);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void connect(String portName) throws Exception {
		CommPortIdentifier portIdentifier = CommPortIdentifier
				.getPortIdentifier(portName);
		if (portIdentifier.isCurrentlyOwned()) {
			System.out.println("Error: Port is currently in use");
		} else {
			CommPort commPort = portIdentifier.open(this.getClass().getName(),
					2000);

			if (commPort instanceof SerialPort) {
				SerialPort serialPort = (SerialPort) commPort;
				serialPort.setSerialPortParams(57600, SerialPort.DATABITS_8,
						SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

				InputStream in = serialPort.getInputStream();
//				OutputStream out = serialPort.getOutputStream();

				(new Thread(new SerialReader(in))).start();
//				(new Thread(new SerialWriter(out))).start();

			} else {
				System.out
				.println("Error: Only serial ports are handled by this example.");
			}
		}
	}

	public void sendMessage(String message){
		this.message = message;
		
	}
	
	
	/** */
	public class SerialWriter implements Runnable {
		OutputStream out;

		public SerialWriter(OutputStream out) {
			this.out = out;
		}
		
		public void run() {
			try {
				this.out.write(message.getBytes(Charset.forName("US-ASCII")));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


	/** */
	public class SerialReader implements Runnable {
		InputStream in;
	
		public SerialReader(InputStream in) {
			this.in = in;
		}
	
		public void run() {
			byte[] buffer = new byte[1024];
			int len = -1;
			try {
				while ((len = this.in.read(buffer)) > -1) {
					log.append(new String(buffer, 0, len));
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

//	public static void main(String[] args) {
//		try {
//			(new SerialComm()).connect("COM3");
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
}